import React, { useState, useEffect, ReactNode } from "react";
import { Button, Modal, message, Alert } from "antd";
import { isObject } from "utils/cmsTransform";
import CodeMirror from '@uiw/react-codemirror';
import 'codemirror/addon/display/autorefresh';
import 'codemirror/addon/comment/comment';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/keymap/sublime';
import 'codemirror/theme/monokai.css';
import "./index.scss";

interface IVCodeEditorProps {
    btnText: string;
    btnExtra?: {[key: string]: any};
    onChange: (options: any) => void;
    value?: string;
    alertMessage?: ReactNode;
}
const baseCodeTemplate = `{
    rules: [
        {
            validator: (rules, values, callback) => {
                console.log("这是示例规则.");
                callback();
            }
        }
    ]
}`
const VCodeEditor: React.FC<IVCodeEditorProps> = (props) => {
    const { value, alertMessage } = props;
    const [ visible, setVisible ] = useState<boolean>(false);
    const [ code, setCode ] = useState(value || baseCodeTemplate)
    const { btnText, btnExtra } = props;
    useEffect(() => {
        value && setCode(value)
    }, [value])
    const submitCode = () => {
        try {
            const trulyCode = eval(`(${code})`);
            console.log(trulyCode)
            if(isObject(trulyCode)){
                props.onChange(trulyCode);
                setVisible(!visible)
                return
            }
            throw new Error("配置数据不是JS对象")
        }catch(err){
            console.error(err)
            message.error("解析Code为Js对象失败，请检查是否存在语法错误!");
        }
    }
    return (<div className="v-code-editor-wrapper">
        <Button {...btnExtra} onClick={() => setVisible(!visible)}>{btnText}</Button>
        <Modal
            visible={visible}
            title={null}
            closable={false}
            okText={"保存编辑配置"}
            cancelText={"取消"}
            onOk={() => submitCode()}
            onCancel={() => setVisible(!visible)}
            width={800}
        >
            {
                alertMessage && <Alert message={alertMessage} type="info" showIcon style={{marginBottom: 16}} />
            }
            <CodeMirror
                value={code}
                height={650}
                onChange={(instance) => {
                    setCode(instance.doc.getValue())
                }}
                options={{
                    theme: 'monokai',
                    keyMap: 'sublime',
                    mode: 'jsx',
                }}
            />
        </Modal>
    </div>)
}

export default VCodeEditor;